package cake.srcprojector.service;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import cake.srcprojector.SrcProjectorConfigurationRuntimeException;
import cake.srcprojector.SrcProjectorRuntimeException;
import cake.srcprojector.model.Page;


public class PageService {
	private Marshaller marshaller = null;
	private Unmarshaller unmarshaller = null;
	
	
	public PageService() throws SrcProjectorConfigurationRuntimeException {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(Page.class);
			
			marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			
			unmarshaller = jaxbContext.createUnmarshaller();
		} catch (JAXBException e) {
			throw new SrcProjectorConfigurationRuntimeException(e);
		}
	}
	
	
	public Page parsePage(File pageFile) throws SrcProjectorRuntimeException {
		try {
			return (Page)unmarshaller.unmarshal(pageFile);
		} catch (JAXBException e) {
			throw new SrcProjectorRuntimeException(e);
		}
	}
	
	
	public void writePage(Page page, File pageFile) throws SrcProjectorRuntimeException {
		try {
			marshaller.marshal(page, pageFile);
		} catch (JAXBException e) {
			throw new SrcProjectorRuntimeException(e);
		}
	}
	
	
}
